package com.hunan.chinamobile.manager;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hunan.chinamobile.core.BaseController;
import com.hunan.chinamobile.core.Result;
import com.hunan.chinamobile.core.ResultGenerator;
import com.hunan.chinamobile.dto.DeviceDTO;
import com.hunan.chinamobile.model.Device;
import com.hunan.chinamobile.model.DeviceData;
import com.hunan.chinamobile.onenet.OneNetBuilder;
import com.hunan.chinamobile.service.DeviceDataService;
import com.hunan.chinamobile.service.DeviceService;
import com.hunan.chinamobile.util.BaiduUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/device")
public class DeviceController extends BaseController{

    static Logger logger = LoggerFactory.getLogger(DeviceController.class);

    @Resource
    private DeviceService deviceService;
    @Resource
    private DeviceDataService deviceDataService;

    @PostMapping
    public Result add(@RequestBody Device device){
        if(device == null
                || StringUtils.isEmpty(device.getNbName().replace(" ","").trim())
                || StringUtils.isEmpty(device.getDeviceId().replace(" ","").trim())
                || StringUtils.isEmpty(device.getImei())
                || StringUtils.isEmpty(device.getImsi())){
            return ResultGenerator.genFailResult("参数为空！");
        }

        Device dbObj = deviceService.findByDeviceId(device.getDeviceId());
        if(dbObj != null){
            return ResultGenerator.genFailResult("该设备ID已存在！");
        }
        Device nameDB = deviceService.findByName(device.getNbName());
        if(nameDB != null){
            return ResultGenerator.genFailResult("该设备名称已存在！");
        }
        device.setOnlineState(false);
        device.setState(0);
        device.setId(UUID.randomUUID().toString());
        device.setCreatedAt(new Date());
        device.setUpdatedAt(new Date());
        if(!StringUtils.isEmpty(device.getAddress())){
            Map<String,Double> pointMap = BaiduUtil.getPoint(device.getAddress());
            device.setLat(pointMap.get("lat"));
            device.setLng(pointMap.get("lng"));
        }

        // 同步给OneNet平台创建设备
        String ontId = OneNetBuilder.createDevice(device.getNbName(),device.getImei(),device.getImsi());
        if(StringUtils.isEmpty(ontId)){
            return ResultGenerator.genFailResult("同步OneNet平台未成功，请重试！");
        }else {
            device.setOneNetId(Integer.parseInt(ontId));
            deviceService.save(device);
        }
        logger.info("==> 新增设备 "+ JSON.toJSONString(device));
        return ResultGenerator.genSuccessResult();
    }

    @PutMapping
    public Result update(@RequestBody Device device){
        if(device == null || StringUtils.isEmpty(device.getNbName())
                || StringUtils.isEmpty(device.getDeviceId())
                || StringUtils.isEmpty(device.getId())) {
            return ResultGenerator.genFailResult("参数为空！");
        }
        Device dbObj = deviceService.findByDeviceId(device.getDeviceId());
        if(dbObj != null && !dbObj.getId().equals(device.getId())){
            return ResultGenerator.genFailResult("设备ID冲突！");
        }
        Device nameDB = deviceService.findByName(device.getNbName());
        if(nameDB != null && !nameDB.getId().equals(device.getId())){
            return ResultGenerator.genFailResult("设备名称冲突！");
        }
        Device updateD = deviceService.findById(device.getId());
        if(!StringUtils.isEmpty(device.getBsId())) {
            updateD.setBsId(device.getBsId());
        }
        if(!StringUtils.isEmpty(device.getAddress())){
            Map<String,Double> pointMap = BaiduUtil.getPoint(device.getAddress());
            device.setLat(pointMap.get("lat"));
            device.setLng(pointMap.get("lng"));
        }
        updateD.setLat(device.getLat());
        updateD.setLng(device.getLng());
        updateD.setAddress(device.getAddress());
        updateD.setDeviceId(device.getDeviceId());
        updateD.setNbName(device.getNbName());
        updateD.setUpdatedAt(new Date());
        deviceService.update(updateD);
        return ResultGenerator.genSuccessResult();
    }


    @DeleteMapping("/{id}")
    public Result del(@PathVariable String id){
        Device device = deviceService.findById(id);
        if(device == null) return ResultGenerator.genFailResult("该设备不存在");
        int i = OneNetBuilder.delDevice(device.getOneNetId().toString());
        if(i == 1)
            deviceService.delById(id);
        else
            return ResultGenerator.genFailResult("删除设备失败！");
        logger.info("==> 删除设备 "+JSON.toJSONString(device));
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/info/{id}")
    public Result info(@PathVariable String id){
        if(StringUtils.isEmpty(id)){
            return ResultGenerator.genFailResult("id为空");
        }
       DeviceDTO dto = deviceService.findDTO(id);
       if(dto == null)
           return ResultGenerator.genFailResult("该设备不存在");
       return ResultGenerator.genSuccessResult(dto);
    }

    /**
     *
     * @param request
     * @param response
     * @param cityId  城市ID
     * @param bsId    基站ID
     * @param online 设备在线状态，null-全部，0-离线，1-在线
     * @param state  设备状态，null-全部，0-未知,1-正常，2-报警
     * @param page
     * @param size
     * @return
     */
    @GetMapping
    public Result list(HttpServletRequest request, HttpServletResponse response,
                       @RequestParam(required = false) String dn,
                       @RequestParam(required = false) String cityId,
                       @RequestParam(required = false) String bsId,
                       @RequestParam(required = false) Integer online,
                       @RequestParam(required = false) Integer state,
                       @RequestParam(name = "page", defaultValue = "1") Integer page,
                       @RequestParam(name = "size", defaultValue = "20") Integer size){
        if(StringUtils.isEmpty(cityId)){
            cityId = getCityId(request, response);
        }
        PageHelper.startPage(page,size);
        List<DeviceDTO> deviceDTOS = deviceService.findList(cityId, bsId, dn,online, state);
        PageInfo<DeviceDTO> pageInfo = new PageInfo<>(deviceDTOS);
        if(deviceDTOS.size() > 0){
            for(DeviceDTO dto : deviceDTOS){
                List<DeviceData> dds = deviceDataService.findByDeviceId(dto.getDeviceId());
                if(dds == null || dds.size() <= 0){
                    dto.setUpdatedAt(null);
                }else{
                    dto.setUpdatedAt(dds.get(0).getCreatedAt());
                }
            }
        }
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @GetMapping("/all")
    public Result all(HttpServletRequest request, HttpServletResponse response,
                      @RequestParam(required = false) String bsId){
        String cityId = getCityId(request, response);
        if(StringUtils.isEmpty(bsId)){
            return ResultGenerator.genFailResult("bsId参数为空！");
        }
        return ResultGenerator.genSuccessResult(deviceService.findList(cityId,bsId,null,null,null));
    }
}
